package edu.sysu.cshare.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import edu.sysu.cshare.control.HomeworkManager;
import edu.sysu.cshare.control.UserManager;
import edu.sysu.cshare.model.Course;
import edu.sysu.cshare.model.Homework;
import edu.sysu.cshare.util.gui.GUI;
import java.awt.Color;

public class Dlg_HomeworkDetail extends JDialog {

	private JPanel contentPanel = new JPanel();
	private JTextField tfDescrp;
	private JTextField tfTeacherName;
	private JTextField tfSize;
	private JTextField tfExt;
	private JTextField tfRemark;
	private JTextField tfMethod;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH点");
	private Homework homework;
	private HomeworkManager homeworkManager;
	private JFormattedTextField fmttxStart;
	private JFormattedTextField fmttxDue;
	private JCheckBox chkboxByGroup;
	private JComboBox cmboxCoure;
	protected boolean create;
	private JLabel lblNewLabel_8;
	private JLabel lblStatus;
	private JTextField tfPath;
	private JButton btnSaveChange;
	private JButton btnBatchDownload;

	

	/**
	 * 初始化作业详情对话框
	 * 
	 * @param homework
	 *            若不为空则是用来查看或修改作业项 若为空则是用来创建新的作业项
	 * @param homeworkManager
	 *            不能为空
	 */

	public Dlg_HomeworkDetail(Homework homework,
			final HomeworkManager homeworkManager) {
		this.homework = homework;
		this.homeworkManager = homeworkManager;
		if (homework == null)
			create = true;
		setLocationRelativeTo(null);
		setBounds(100, 100, 564, 466);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBackground(new Color(211, 211, 211));
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		GridBagLayout gbl_contentPanel = new GridBagLayout();
		gbl_contentPanel.columnWidths = new int[] { 0, 47, 0, 47, 0 };
		gbl_contentPanel.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
		gbl_contentPanel.columnWeights = new double[] { 1.0, 1.0, 0.0, 1.0,
				Double.MIN_VALUE };
		gbl_contentPanel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0,
				0.0, 0.0, Double.MIN_VALUE };
		contentPanel.setLayout(gbl_contentPanel);
		{
			JLabel lblNewLabel = new JLabel(Pnl_Homework.Naming.getCourseName());
			GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
			gbc_lblNewLabel.anchor = GridBagConstraints.EAST;
			gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
			gbc_lblNewLabel.gridx = 0;
			gbc_lblNewLabel.gridy = 0;
			contentPanel.add(lblNewLabel, gbc_lblNewLabel);
		}
		{
			int coursecnt = homeworkManager.getActor().getClazz().getCourses()
					.size();
			Course[] coures = homeworkManager.getActor().getClazz()
					.getCourses().toArray(new Course[coursecnt]);
			cmboxCoure = new JComboBox(coures);
			cmboxCoure.setEditable(false);
			cmboxCoure.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					JComboBox cb = (JComboBox) e.getSource();
					Course c = (Course) cb.getSelectedItem();
					tfTeacherName.setText(c.getTeacher().getName());
				}
			});

			GridBagConstraints gbc_cmboxCoure = new GridBagConstraints();
			gbc_cmboxCoure.insets = new Insets(0, 0, 5, 5);
			gbc_cmboxCoure.fill = GridBagConstraints.HORIZONTAL;
			gbc_cmboxCoure.gridx = 1;
			gbc_cmboxCoure.gridy = 0;
			contentPanel.add(cmboxCoure, gbc_cmboxCoure);
		}
		{
			JLabel lblNewLabel_1 = new JLabel("任课老师");
			GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
			gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
			gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
			gbc_lblNewLabel_1.gridx = 2;
			gbc_lblNewLabel_1.gridy = 0;
			contentPanel.add(lblNewLabel_1, gbc_lblNewLabel_1);
		}
		{
			tfTeacherName = new JTextField();
			tfTeacherName.setEditable(false);
			tfTeacherName.setColumns(10);
			GridBagConstraints gbc_tfTeacherName = new GridBagConstraints();
			gbc_tfTeacherName.insets = new Insets(0, 0, 5, 0);
			gbc_tfTeacherName.fill = GridBagConstraints.HORIZONTAL;
			gbc_tfTeacherName.gridx = 3;
			gbc_tfTeacherName.gridy = 0;
			contentPanel.add(tfTeacherName, gbc_tfTeacherName);
		}
		{
			JLabel label = new JLabel("作业描述");
			GridBagConstraints gbc_label = new GridBagConstraints();
			gbc_label.insets = new Insets(0, 0, 5, 5);
			gbc_label.anchor = GridBagConstraints.EAST;
			gbc_label.gridx = 0;
			gbc_label.gridy = 1;
			contentPanel.add(label, gbc_label);
		}
		{
			tfDescrp = new JTextField();
			GridBagConstraints gbc_tfDescrp = new GridBagConstraints();
			gbc_tfDescrp.gridwidth = 3;
			gbc_tfDescrp.insets = new Insets(0, 0, 5, 0);
			gbc_tfDescrp.fill = GridBagConstraints.HORIZONTAL;
			gbc_tfDescrp.gridx = 1;
			gbc_tfDescrp.gridy = 1;
			contentPanel.add(tfDescrp, gbc_tfDescrp);
			tfDescrp.setColumns(10);
		}
		{
			JLabel lblNewLabel_2 = new JLabel("开始时间");
			lblNewLabel_2.setToolTipText(GUI.getDateTooltip());
			GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
			gbc_lblNewLabel_2.anchor = GridBagConstraints.EAST;
			gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 5);
			gbc_lblNewLabel_2.gridx = 0;
			gbc_lblNewLabel_2.gridy = 2;
			contentPanel.add(lblNewLabel_2, gbc_lblNewLabel_2);
		}
		{
			fmttxStart = new JFormattedTextField(sdf);
			fmttxStart.setToolTipText(GUI.getDateTooltip());
			GridBagConstraints gbc_fmttxStart = new GridBagConstraints();
			gbc_fmttxStart.insets = new Insets(0, 0, 5, 5);
			gbc_fmttxStart.fill = GridBagConstraints.HORIZONTAL;
			gbc_fmttxStart.gridx = 1;
			gbc_fmttxStart.gridy = 2;
			contentPanel.add(fmttxStart, gbc_fmttxStart);
		}
		{
			JLabel lblNewLabel_3 = new JLabel("结束时间");
			lblNewLabel_3.setToolTipText(GUI.getDateTooltip());
			GridBagConstraints gbc_lblNewLabel_3 = new GridBagConstraints();
			gbc_lblNewLabel_3.anchor = GridBagConstraints.EAST;
			gbc_lblNewLabel_3.insets = new Insets(0, 0, 5, 5);
			gbc_lblNewLabel_3.gridx = 2;
			gbc_lblNewLabel_3.gridy = 2;
			contentPanel.add(lblNewLabel_3, gbc_lblNewLabel_3);
		}
		{
			fmttxDue = new JFormattedTextField(sdf);
			fmttxDue.setToolTipText(GUI.getDateTooltip());
			GridBagConstraints gbc_fmttxDue = new GridBagConstraints();
			gbc_fmttxDue.insets = new Insets(0, 0, 5, 0);
			gbc_fmttxDue.fill = GridBagConstraints.HORIZONTAL;
			gbc_fmttxDue.gridx = 3;
			gbc_fmttxDue.gridy = 2;
			contentPanel.add(fmttxDue, gbc_fmttxDue);
		}
		{
			JLabel label = new JLabel("大小限制");
			GridBagConstraints gbc_label = new GridBagConstraints();
			gbc_label.anchor = GridBagConstraints.EAST;
			gbc_label.insets = new Insets(0, 0, 5, 5);
			gbc_label.gridx = 0;
			gbc_label.gridy = 3;
			contentPanel.add(label, gbc_label);
		}
		{
			tfSize = new JTextField();
			tfSize.setColumns(10);
			GridBagConstraints gbc_tfSize = new GridBagConstraints();
			gbc_tfSize.insets = new Insets(0, 0, 5, 5);
			gbc_tfSize.fill = GridBagConstraints.HORIZONTAL;
			gbc_tfSize.gridx = 1;
			gbc_tfSize.gridy = 3;
			contentPanel.add(tfSize, gbc_tfSize);
		}
		{
			JLabel lblNewLabel_4 = new JLabel("格式限制");
			GridBagConstraints gbc_lblNewLabel_4 = new GridBagConstraints();
			gbc_lblNewLabel_4.anchor = GridBagConstraints.EAST;
			gbc_lblNewLabel_4.insets = new Insets(0, 0, 5, 5);
			gbc_lblNewLabel_4.gridx = 2;
			gbc_lblNewLabel_4.gridy = 3;
			contentPanel.add(lblNewLabel_4, gbc_lblNewLabel_4);
		}
		{
			tfExt = new JTextField();
			tfExt.setColumns(10);
			GridBagConstraints gbc_tfExt = new GridBagConstraints();
			gbc_tfExt.insets = new Insets(0, 0, 5, 0);
			gbc_tfExt.fill = GridBagConstraints.HORIZONTAL;
			gbc_tfExt.gridx = 3;
			gbc_tfExt.gridy = 3;
			contentPanel.add(tfExt, gbc_tfExt);
		}
		{
			JLabel lblNewLabel_7 = new JLabel("提交方法");
			GridBagConstraints gbc_lblNewLabel_7 = new GridBagConstraints();
			gbc_lblNewLabel_7.anchor = GridBagConstraints.EAST;
			gbc_lblNewLabel_7.insets = new Insets(0, 0, 5, 5);
			gbc_lblNewLabel_7.gridx = 0;
			gbc_lblNewLabel_7.gridy = 4;
			contentPanel.add(lblNewLabel_7, gbc_lblNewLabel_7);
		}
		{
			tfMethod = new JTextField();
			GridBagConstraints gbc_tfMethod = new GridBagConstraints();
			gbc_tfMethod.insets = new Insets(0, 0, 5, 5);
			gbc_tfMethod.fill = GridBagConstraints.HORIZONTAL;
			gbc_tfMethod.gridx = 1;
			gbc_tfMethod.gridy = 4;
			contentPanel.add(tfMethod, gbc_tfMethod);
			tfMethod.setColumns(10);
		}
		{
			chkboxByGroup = new JCheckBox("分组提交");
			GridBagConstraints gbc_rdbtnByGroup = new GridBagConstraints();
			gbc_rdbtnByGroup.insets = new Insets(0, 0, 5, 0);
			gbc_rdbtnByGroup.gridx = 3;
			gbc_rdbtnByGroup.gridy = 4;
			contentPanel.add(chkboxByGroup, gbc_rdbtnByGroup);
		}
		{
			JLabel lblNewLabel_6 = new JLabel("备注事项");
			GridBagConstraints gbc_lblNewLabel_6 = new GridBagConstraints();
			gbc_lblNewLabel_6.anchor = GridBagConstraints.EAST;
			gbc_lblNewLabel_6.insets = new Insets(0, 0, 5, 5);
			gbc_lblNewLabel_6.gridx = 0;
			gbc_lblNewLabel_6.gridy = 5;
			contentPanel.add(lblNewLabel_6, gbc_lblNewLabel_6);
		}
		{
			tfRemark = new JTextField();
			GridBagConstraints gbc_tfRemark = new GridBagConstraints();
			gbc_tfRemark.gridwidth = 3;
			gbc_tfRemark.insets = new Insets(0, 0, 5, 0);
			gbc_tfRemark.fill = GridBagConstraints.HORIZONTAL;
			gbc_tfRemark.gridx = 1;
			gbc_tfRemark.gridy = 5;
			contentPanel.add(tfRemark, gbc_tfRemark);
			tfRemark.setColumns(10);
		}
		{
			lblNewLabel_8 = new JLabel("保存路径");
			GridBagConstraints gbc_lblNewLabel_8 = new GridBagConstraints();
			gbc_lblNewLabel_8.insets = new Insets(0, 0, 0, 5);
			gbc_lblNewLabel_8.anchor = GridBagConstraints.EAST;
			gbc_lblNewLabel_8.gridx = 0;
			gbc_lblNewLabel_8.gridy = 6;
			contentPanel.add(lblNewLabel_8, gbc_lblNewLabel_8);
		}
		{
			tfPath = new JTextField();
			GridBagConstraints gbc_tfPath = new GridBagConstraints();
			gbc_tfPath.gridwidth = 3;
			gbc_tfPath.insets = new Insets(0, 0, 0, 5);
			gbc_tfPath.fill = GridBagConstraints.HORIZONTAL;
			gbc_tfPath.gridx = 1;
			gbc_tfPath.gridy = 6;
			contentPanel.add(tfPath, gbc_tfPath);
			tfPath.setColumns(10);
		}

		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				lblStatus = new JLabel("当前状态:未保存");
				buttonPane.add(lblStatus);
			}
			{
				btnSaveChange = new JButton("保存修改");
				btnSaveChange.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						try {
							validateValue();

							if (!create) {
								// 仅仅更改
								// 更新作业属性信息
								updateValue();
								Dlg_HomeworkDetail.this.homeworkManager
										.merge(Dlg_HomeworkDetail.this.homework);
							} else {
								try {
									// 创建新的项目
									Dlg_HomeworkDetail.this.homework = new Homework();
									// 更新作业属性信息
									updateValue();
									Dlg_HomeworkDetail.this.homeworkManager
											.addItem(Dlg_HomeworkDetail.this.homework);
								} catch (Exception e1) {
									JOptionPane.showMessageDialog(null,
											e1.getMessage());
								}
							}
							JOptionPane.showMessageDialog(null, "保存成功");
						} catch (Exception e2) {
							JOptionPane.showMessageDialog(null, e2.getMessage());
						}

					}

				});
				buttonPane.add(btnSaveChange);
			}
			{
				btnBatchDownload = new JButton("批量下载");
				btnBatchDownload.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						String local = null;
						try {
							JFileChooser chooser = new JFileChooser();
							chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
							if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
								homeworkManager.batchDownload(
										Dlg_HomeworkDetail.this.homework,
										chooser.getSelectedFile().toString());
								JOptionPane.showMessageDialog(null, "批量下载成功");
							} else {
								// System.out.println("No Selection ");
							}
						} catch (Exception e1) {
							JOptionPane.showMessageDialog(null, e1.getMessage());
						}

					}
				});
				buttonPane.add(btnBatchDownload);
			}
			{
				JButton bntDownload = new JButton("下载");
				bntDownload.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						String local = null;
						try {
							JFileChooser chooser = new JFileChooser();
							chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
							if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
								homeworkManager.downloadMine(
										Dlg_HomeworkDetail.this.homework,
										chooser.getSelectedFile().toString());
								JOptionPane.showMessageDialog(null, "保存成功");
							} else {
								// System.out.println("No Selection ");
							}
						} catch (Exception e1) {
							JOptionPane.showMessageDialog(null, e1.getMessage());
						}

					}
				});
				buttonPane.add(bntDownload);

			}
			{
				JButton btnOK = new JButton("确定");
				btnOK.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						closeDialog();
						System.out.println("EXIT");
					}
				});
				buttonPane.add(btnOK);
				getRootPane().setDefaultButton(btnOK);
			}
		}
		setValue();
		setEditable();
	}

	private void validateValue() throws Exception {
		if ((Date) fmttxDue.getValue() == null) {
			throw new Exception("截止日期不能为空");
		} else if ((Date) fmttxStart.getValue() == null) {
			throw new Exception("开始日期不能为空");
		} else if (((Date) fmttxDue.getValue()).before(((Date) fmttxStart
				.getValue()))) {
			throw new Exception("截止日期非法");
		} else if (tfDescrp.getText() == null
				|| tfDescrp.getText().length() == 0) {
			throw new Exception("作业描述不能为空");
		}

	}

	private void closeDialog() {
		this.dispose();
	}

	private void updateValue() {
		homework.setCourse((Course) cmboxCoure.getSelectedItem());
		homework.setDescrip(tfDescrp.getText());
		Calendar startDate = Calendar.getInstance();
		startDate.setTime((Date) fmttxStart.getValue());
		Calendar dueDate = Calendar.getInstance();
		dueDate.setTime((Date) fmttxDue.getValue());
		homework.setStartDate(startDate);
		homework.setDueDate(dueDate);
		
		int a = 0;
		if (tfSize.getText() != null && tfSize.getText().length() > 0)
			a = Integer.parseInt(tfSize.getText().substring(0,
					tfSize.getText().lastIndexOf(" ")));
		homework.setMaxSize(a);
		homework.setExtRestrict(tfExt.getText());
		homework.setSubmitMethod(tfMethod.getText());
		homework.setSubmitByGroup(chkboxByGroup.isSelected());
		homework.setRemark(tfRemark.getText());
		homework.setDirPath(tfPath.getText());
	}

	private void setEditable() {
		if (!homeworkManager.getActor().canManageHomework()) {
			fmttxDue.setEditable(false);
			fmttxStart.setEditable(false);
			tfDescrp.setEditable(false);
			tfExt.setEditable(false);
			tfMethod.setEditable(false);
			tfPath.setEditable(false);
			tfRemark.setEditable(false);
			tfSize.setEditable(false);
			btnBatchDownload.setVisible(false);
			btnSaveChange.setVisible(false);
			chkboxByGroup.setEnabled(false);
		}

	}

	private void setValue() {
		if (homework == null) {
			System.out.println("home work null");
			Calendar cal = Calendar.getInstance();
			fmttxStart.setValue(cal.getTime());
			tfTeacherName.setText(((Course) cmboxCoure.getSelectedItem())
					.getTeacher().getName());
			cal.add(Calendar.DAY_OF_YEAR, 7);
			fmttxDue.setValue(cal.getTime());

			//
		} else {
			String groupStat = null;
			String stuStat = "当前状态提交" + homework.calcSubedStuCount() + "/"
					+ homework.getCourse().getStudents().size() + "人  ";
			if (homework.getSubmitByGroup()) {

				try {
					stuStat += homework.calcSubedGroupCount() + "/"
							+ homework.getCourse().getGroups().size() + " 组";
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			lblStatus.setText(stuStat);
			cmboxCoure.setSelectedItem(homework.getCourse());
			cmboxCoure.setEnabled(false);
			fmttxDue.setValue(homework.getDueDate().getTime());

			if (homework.getStartDate() != null) {
				fmttxStart.setValue(homework.getStartDate().getTime());
			}
			tfDescrp.setText(homework.getDescrip());
			tfExt.setText(homework.getExtRestrict());
			tfMethod.setText(homework.getSubmitMethod());
			tfRemark.setText(homework.getRemark());
			tfSize.setText(String.valueOf(homework.getMaxSize()) + " KB");
			tfTeacherName.setText(homework.getCourse().getTeacher().getName());
			tfPath.setText(homework.getDirPath());
			chkboxByGroup.setSelected(homework.getSubmitByGroup());
		}

	}

}
